<?php

// TTTTTTTTTTTTTTTTTTTTTTT                  MMMMMMMM               MMMMMMMM                                CCCCCCCCCCCCMMMMMMMM               MMMMMMMM  SSSSSSSSSSSSSSS 
// T:::::::::::::::::::::T                  M:::::::M             M:::::::M                             CCC::::::::::::M:::::::M             M:::::::MSS:::::::::::::::S
// T:::::::::::::::::::::T                  M::::::::M           M::::::::M                           CC:::::::::::::::M::::::::M           M::::::::S:::::SSSSSS::::::S
// T:::::TT:::::::TT:::::T                  M:::::::::M         M:::::::::M                          C:::::CCCCCCCC::::M:::::::::M         M:::::::::S:::::S     SSSSSSS
// TTTTTT  T:::::T  TTTTTppppp   ppppppppp  M::::::::::M       M::::::::::M   eeeeeeeeeeee          C:::::C       CCCCCM::::::::::M       M::::::::::S:::::S            
//         T:::::T       p::::ppp:::::::::p M:::::::::::M     M:::::::::::M ee::::::::::::ee       C:::::C             M:::::::::::M     M:::::::::::S:::::S            
//         T:::::T       p:::::::::::::::::pM:::::::M::::M   M::::M:::::::Me::::::eeeee:::::ee     C:::::C             M:::::::M::::M   M::::M:::::::MS::::SSSS         
//         T:::::T       pp::::::ppppp::::::M::::::M M::::M M::::M M::::::e::::::e     e:::::e     C:::::C             M::::::M M::::M M::::M M::::::M SS::::::SSSSS    
//         T:::::T        p:::::p     p:::::M::::::M  M::::M::::M  M::::::e:::::::eeeee::::::e     C:::::C             M::::::M  M::::M::::M  M::::::M   SSS::::::::SS  
//         T:::::T        p:::::p     p:::::M::::::M   M:::::::M   M::::::e:::::::::::::::::e      C:::::C             M::::::M   M:::::::M   M::::::M      SSSSSS::::S 
//         T:::::T        p:::::p     p:::::M::::::M    M:::::M    M::::::e::::::eeeeeeeeeee       C:::::C             M::::::M    M:::::M    M::::::M           S:::::S
//         T:::::T        p:::::p    p::::::M::::::M     MMMMM     M::::::e:::::::e                 C:::::C       CCCCCM::::::M     MMMMM     M::::::M           S:::::S
//       TT:::::::TT      p:::::ppppp:::::::M::::::M               M::::::e::::::::e                 C:::::CCCCCCCC::::M::::::M               M::::::SSSSSSS     S:::::S
//       T:::::::::T      p::::::::::::::::pM::::::M               M::::::Me::::::::eeeeeeee          CC:::::::::::::::M::::::M               M::::::S::::::SSSSSS:::::S
//       T:::::::::T      p::::::::::::::pp M::::::M               M::::::M ee:::::::::::::e            CCC::::::::::::M::::::M               M::::::S:::::::::::::::SS 
//       TTTTTTTTTTT      p::::::pppppppp   MMMMMMMM               MMMMMMMM   eeeeeeeeeeeeee               CCCCCCCCCCCCMMMMMMMM               MMMMMMMMSSSSSSSSSSSSSSS   
//                        p:::::p                                                                                                                                       
//                        p:::::p                                                                                                                                       
//                       p:::::::p                                                                                                                                      
//                       p:::::::p                                                                                                                                      
//                       p:::::::p                                                                                                                                      
//                       ppppppppp                                                                                                                                      

//  _____      __  __         ____ __  __ ____  
// |_   __ __ |  \/  | ___   / ___|  \/  / ___|     | AUTHOR: Xiaohe
//   | || '_ \| |\/| |/ _ \ | |   | |\/| \___ \     | EMAIL: 496631085@qq.com
//   | || |_) | |  | |  __/ | |___| |  | |___) |    | WECHAT: he4966
//   |_|| .__/|_|  |_|\___|  \____|_|  |_|____/     | DATETIME: 2023/07/13
//      |_|                                         | TpMeCMS

declare(strict_types=1);

namespace ImiApp\ApiServer\Api\Controller\store;

use Imi\Db\Db;
use Imi\Server\Http\Route\Annotation\Action;
use Imi\Server\Http\Route\Annotation\Controller;
use Imi\Server\Http\Route\Annotation\Route;
use Psr\Http\Message\ResponseInterface;
use Imi\Aop\Annotation\Inject;
// use Phpben\Imi\Validate\Annotation\Validate;
use Phpben\Imi\Auth\Annotation\Auth;


/**
 * 统计
 * @Auth(name="token",nologin={"no"})
 * @Controller("/store.bill/")
 */
class Bill extends StoreOwner
{
    protected $noNeedLogin = ['no'];
    protected $noNeedRight = ['*'];

    /**
     * 获取店铺统计
     *
     * @return void
     * @Action
     */
    public function get_bill1()
    {
        $this->init();
        $where_com['store_id'] = $this->store_id;


        $yesterday_s = strtotime('yesterday');
        $yesterday_e = $yesterday_s + 86399;

        $today_s = strtotime('today');
        $today_e = $today_s + 86399;


        //今日订单数
        $today_order_num = Db::name('order_item')
            ->whereEx($where_com)
            ->where('createtime', '<=', $today_e)
            ->where('createtime', '>=', $today_s)
            ->count();
        //昨日订单数
        $yesterday_order_num = Db::name('order_item')
            ->whereEx($where_com)
            ->where('createtime', '<=', $yesterday_e)
            ->where('createtime', '>=', $yesterday_s)
            ->count();

        //今日访客数
        $today_storeview_num = Db::name('viewlog')
            ->where('viewstatus_id', '=', STORE)
            ->where('public_id', '=', $this->store_id)
            ->where('time', '<=', $today_e)
            ->where('time', '>=', $today_s)
            // ->where('user_id')//time
            ->count();


        //昨日访客数
        $yesterday_storeview_num = Db::name('viewlog')
            ->where('viewstatus_id', '=', STORE)
            ->where('public_id', '=', $this->store_id)
            ->where('time', '<=', $yesterday_e)
            ->where('time', '>=', $yesterday_s)
            // ->where('user_id')//time
            ->count();




        $data['today_order_num'] = $today_order_num ? $today_order_num : 0;
        $data['yesterday_order_num'] = $yesterday_order_num ? $yesterday_order_num : 0;
        $data['today_storeview_num'] = $today_storeview_num ? $today_storeview_num : 0;
        $data['yesterday_storeview_num'] = $yesterday_storeview_num ? $yesterday_storeview_num : 0;
        $data['store_likes_num'] = $this->store->likes;



        return $this->success('统计', $data);
    }


    /**
     * 获取店铺财务统计
     *
     *
     * @param string $typestatus_id 类型id
     * @param string $s_date 开始时间
     * @param string $e_date 结束时间
     * @return void
     * @Action
     */
    public function finance($typestatus_id = null, $s_date = null, $e_date = null)
    {


        $this->init();
        $where_com_log['store_id'] = $this->store_id;

        if ($typestatus_id) {
            $where_com_log['typestatus_id'] = $typestatus_id;
        }
        if ($s_date && $e_date) {
        }

        $where_com_order['store_id'] = $this->store_id;
        // $累计收入money = Db::name('order_item')
        //     ->whereEx($where_com_order)
        //     ->where('dispatch_status','=','2')//发货状态:0=未发货,1=已发货,2=已收货
        //     ->where('status','=','2')//订单状态:-2=交易关闭,-1=已取消,0=未支付,1=已支付,2=已完成
        //     ->sum();
        $累计收入money = Db::name('store_money_log')
            ->whereEx($where_com_log)
            ->where('status', '=', '2') //状态:0=未知,1=支出,2=收入
            ->sum('money');

        // $累计支出money =Db::name('store_money_log')
        //                 ->whereEx($where_com_log)
        //                 ->where('status','=','1')//状态:0=未知,1=支出,2=收入
        //                 ->sum('money');


        $累计收入shell = Db::name('store_shell_log')
            ->whereEx($where_com_log)
            ->where('status', '=', '2') //状态:0=未知,1=支出,2=收入
            ->sum('shell');

        // $累计支出shell =Db::name('store_shell_log')
        //                 ->whereEx($where_com_log)
        //                 ->where('status','=','1')//状态:0=未知,1=支出,2=收入
        //                 ->sum('shell');



        $累计收入score = Db::name('store_score_log')
            ->whereEx($where_com_log)
            ->where('status', '=', '2') //状态:0=未知,1=支出,2=收入
            ->sum('score');

        // $累计支出score =Db::name('store_score_log')
        //                 ->whereEx($where_com_log)
        //                 ->where('status','=','1')//状态:0=未知,1=支出,2=收入
        //                 ->sum('score');





        $子订单列表 = Db::name('order_item')
            ->whereEx($where_com_order)
            ->where('status', '=', '1') //订单状态:-2=交易关闭,-1=已取消,0=未支付,1=已支付,2=已完成
            ->where('refund_status', '=', 0) //退款状态:-1=拒绝退款,0=无,1=申请中,2=同意
            ->select()->getArray();
        $待收入money = 0;
        $待收入shell = 0;
        $待收入score = 0;
        foreach ($子订单列表 as $key => $order_item) {
            $待收入money += $order_item['total_fee'];
            $待收入shell += ($order_item['item_shell_fee'] * $order_item['goods_num']);
            $待收入score += ($order_item['item_score_fee'] * $order_item['goods_num']);
        }







        return $this->success('', [
            'count_inc_money' => $累计收入money ?? 0, 'count_inc_shell' => $累计收入shell ?? 0, 'count_inc_score' => $累计收入score ?? 0,

            'un_finish_money' => $待收入money ?? 0, 'un_finish_shell' => $待收入shell ?? 0, 'un_finish_score' => $待收入score ?? 0
        ]);
    }

    /**
     * 财务管理上月本月今日
     *
     * @return void
     * @Action
     */
    public function finance2()
    {
        $this->init();
        $where_com['store_id'] = $this->store_id;

        list($当月开始, $当月结束) = $this->GetMonthTime(date('Y-m'));
        list($上月开始, $上月结束) = $this->GetMonthTime(date('Y-m', strtotime('last month')));
        $今日开始 = strtotime(date('Y-m-d'));
        $今日结束 = $今日开始 + 86400;
        // $当月销售money = Db::name('store_money_log')
        //     ->whereEx($where_com)
        //     ->where('createtime', '>=', $当月开始)
        //     ->where('createtime', '<', $当月结束)
        //     ->where('typestatus_id', '=', 20)
        //     ->sum('money');
        
         

        // $上月销售money = Db::name('store_money_log')
        //     ->whereEx($where_com)
        //     ->where('createtime', '>=', $上月开始)
        //     ->where('createtime', '<', $上月结束)
        //     ->where('typestatus_id', '=', 20)
        //     ->sum('money');

       


        // $当月销售shell = Db::name('store_shell_log')
        //     ->whereEx($where_com)
        //     ->where('createtime', '>=', $当月开始)
        //     ->where('createtime', '<', $当月结束)
        //     ->where('typestatus_id', '=', 20)
        //     ->sum('shell');

       


        // $上月销售shell = Db::name('store_shell_log')
        //     ->whereEx($where_com)
        //     ->where('createtime', '>=', $上月开始)
        //     ->where('createtime', '<', $上月结束)
        //     ->where('typestatus_id', '=', 20)
        //     ->sum('shell');

        // $当月销售score = Db::name('store_score_log')
        //     ->whereEx($where_com)
        //     ->where('createtime', '>=', $当月开始)
        //     ->where('createtime', '<', $当月结束)
        //     ->where('typestatus_id', '=', 20)
        //     ->sum('score');

        // $上月销售score = Db::name('store_score_log')
        //     ->whereEx($where_com)
        //     ->where('createtime', '>=', $上月开始)
        //     ->where('createtime', '<', $上月结束)
        //     ->where('typestatus_id', '=', 20)
        //     ->sum('score');



        $今日运费money = Db::name('order')
            ->whereEx($where_com)
            ->where('status', 'in', ['1', '2']) //订单状态:-2=交易关闭,-1=已取消,0=未支付,1=已支付,2=已完成
            ->where('createtime', '>=', $今日开始)
            ->where('createtime', '<=', $今日结束)
            ->sum('dispatch_amount');

        $今日销售money = Db::name('order')
            ->whereEx($where_com)
            ->where('status', 'in', ['1', '2']) //订单状态:-2=交易关闭,-1=已取消,0=未支付,1=已支付,2=已完成
            ->where('createtime', '>=', $今日开始)
            ->where('createtime', '<=', $今日结束)
            ->sum('goods_amount');

        $今日支付money = Db::name('order')
            ->whereEx($where_com)
            ->where('status', 'in', ['1', '2']) //订单状态:-2=交易关闭,-1=已取消,0=未支付,1=已支付,2=已完成
            ->where('createtime', '>=', $今日开始)
            ->where('createtime', '<=', $今日结束)
            ->sum('pay_fee');

        $今日支付shell = Db::name('order')
            ->whereEx($where_com)
            ->where('status', 'in', ['1', '2']) //订单状态:-2=交易关闭,-1=已取消,0=未支付,1=已支付,2=已完成
            ->where('createtime', '>=', $今日开始)
            ->where('createtime', '<=', $今日结束)
            ->sum('shell_fee');

        $今日支付score = Db::name('order')
            ->whereEx($where_com)
            ->where('status', 'in', ['1', '2']) //订单状态:-2=交易关闭,-1=已取消,0=未支付,1=已支付,2=已完成
            ->where('createtime', '>=', $今日开始)
            ->where('createtime', '<=', $今日结束)
            ->sum('score_fee');


        $当月销售money = $this->店铺销售money($this->store_id,$当月开始, $当月结束);
        $上月销售money = $this->店铺销售money($this->store_id,$上月开始, $上月结束);

        $当月销售shell = $this->店铺销售shell($this->store_id,$当月开始, $当月结束);
        $上月销售shell = $this->店铺销售shell($this->store_id,$上月开始, $上月结束);


        $当月销售score = $this->店铺销售score($this->store_id,$当月开始, $当月结束);
        $上月销售score = $this->店铺销售score($this->store_id,$上月开始, $上月结束);

        return $this->success('', [
            'month_money' => $当月销售money ?? 0, 'month_shell' => $当月销售shell ?? 0, 'month_score' => $当月销售score ?? 0,

            'last_month_money' => $上月销售money ?? 0, 'last_month_shell' => $上月销售shell ?? 0, 'last_month_score' => $上月销售score ?? 0,

            'today_count_money' => $今日销售money+$今日运费money ?? 0, 'today_pay_money' => $今日支付money ?? 0, 'today_pay_shell' => $今日支付shell ?? 0, 'today_pay_score' => $今日支付score ?? 0
        ]);
    }





    /**
     * 获取统计邀请
     * @Action
     * @return void
     */
    public function get_count()
    {
        $where['user_id'] = $user_id = $this->auth->user()->id;

        $我邀请的会员数 = Db::name('user')->where('pid', '=', $user_id)->count();
        $invite_user_ids = Db::name('user')->where('pid', '=', $user_id)->column('id');
        $store_num = Db::name('store')->where('user_id', 'in', $invite_user_ids)->count();
        $辅导员店铺 = Db::name('store')->where('pid', '=', $user_id)->count();
        $间接会员数 = 0;
        if ($invite_user_ids) {
            foreach ($invite_user_ids as $key => $id) {
                $temp = Db::name('user')->where('pid', 'in', $invite_user_ids)->count();
                $间接会员数 = $间接会员数 + $temp ? $temp : 0;
            }
        }


        $我邀请的会员数 = $我邀请的会员数 ? $我邀请的会员数 : 0;
        $间接会员数 = $间接会员数 ? $间接会员数 : 0;
        $store_num = $store_num ? $store_num : 0;
        $辅导员店铺 =  $辅导员店铺 ? $辅导员店铺 : 0;
        $data['user_num'] = $我邀请的会员数;
        $data['store_num'] = $store_num;
        $data['indirect_user_num'] = $间接会员数;
        $data['coach_store_num'] =  $辅导员店铺;
        // $data['out'] = Db::name('signlog')->whereEx($where)->where('status','1')->sum('signlog');  
        // $data['this_month_inc'] = Db::name('signlog')->whereEx($where)->whereTime('createtime', 'm')->where('status','2')->sum('signlog');  
        // $data['this_month_dec'] = Db::name('signlog')->whereEx($where)->whereTime('createtime', 'm')->where('status','1')->sum('signlog');  
        return $this->success('统计', $data);
    }

    /**
     * 获取订单列表
     *
     * @param string $status 1=待结算,2=已到账
     * @param integer $page 1
     * @param integer $limit 10
     * @param string $s_date 开始时间
     * @param string $e_date 结束时间
     * @Action
     * @return void
     */
    public function get_order_list(?string $status=null, ?int $page = 1, ?int $limit = 10, $s_date = null, $e_date = null)
    {
        $page = $page ?: 1;
        $limit = $limit ?: 10;
        $this->init();
        $where_com['store_id'] = $this->store_id;

        if($status){
            $where_com['status'] = $status;  
        }else{
            $where_com['status'] = ['in',['1', '2']];  
        }

        if($s_date && $e_date){
            $where_com['createtime'] = ['>=',strtotime($s_date)];
            $list = Db::name('order_item')
            ->whereEx($where_com)
            ->where('createtime','>=',strtotime($s_date))
            ->where('createtime','<=',strtotime($e_date))
            // ->where('status', 'in', ) //订单状态:-2=交易关闭,-1=已取消,0=未支付,1=已支付,2=已完成'
            ->page($page,$limit)
            ->select()->getArray();
        }else{
            $list = Db::name('order_item')
                ->whereEx($where_com)
                // ->where('status', 'in', ['1', '2']) //订单状态:-2=交易关闭,-1=已取消,0=未支付,1=已支付,2=已完成'
                ->page($page,$limit)
                ->orderRaw('createtime desc')
                ->select()->getArray();
        }

        foreach ($list as $key => &$val) {
           $val['date'] = date('Y-m-d H:i',$val['createtime']);
        }
        
        return $this->success('',$list);

    }




    /**
     * 获取邀请会员列表
     *
     * @param integer $page 1
     * @param integer $limit 10
     * @param string $search 搜索
     * @return void
     * @Action
     */
    public function get_invite_user_list(?int $page = 1, ?int  $limit = 10, ?string $search = null)
    {
        $page = $page ? $page : 1;
        $limit = $limit ? $limit : 10;

        $data['pid'] = $this->auth->user()->id;
        if ($search) {
            $data['nickname'] = ['like', "%" . $search . "%"];
        }

        $list = Db::name('user')->orderRaw('id desc')->whereEx($data)->fieldRaw('nickname,avatar,mobile,id,createtime,set_id,wechat_number')->page($page, $limit)->select()->getArray();

        if ($list)
            foreach ($list as $key => &$val) {

                $val['mobile'] = $this->HideMobile($val['mobile']);
                // $this->ChangeFieldData($val);
                $val['date'] = date('Y-m-d H:i', $val['createtime']);
                $val['f'] = 0;
                $val['set_name'] = Db::name('set')->where('id', '=', $val['set_id'])->value('name');
                $val['order'] = Db::name('order_item')
                        ->where('user_id','=',$val['id'])
                        ->where('status','=','2')//订单状态:-2=交易关闭,-1=已取消,0=未支付,1=已支付,2=已完成
                        ->count();
            }
        return $this->success('ok', $list);
    }

    /**
     * 获取邀请店铺列表
     *
     * @param integer $page 1
     * @param integer $limit 10
     * @param string $search 搜索
     * @return void
     * @Action
     */
    public function get_invite_store_list(?int $page = 1, ?int  $limit = 10, ?string $search = null)
    {
        $page = $page ?: 1;
        $limit = $limit ?: 10;


        $invite_user_ids = Db::name('user')->where('pid', '=', $this->auth->user()->id)->column('id');
        if ($search) {
            $data['name'] = ['like', "%" . $search . "%"];
        }
        $data['user_id'] = ['in', $invite_user_ids];

        $list = Db::name('store')->whereEx($data)->page($page, $limit)->orderRaw('id desc')->select()->getArray();
        // ->orderRaw('id desc')->field('nickname,mobile,id,createtime')->page($page, $limit)->select()->getArray();
        if ($list)
            foreach ($list as $key => &$val) {
                // $val['mobile'] = $this->HideMobile($val['mobile']);
                // $this->ChangeFieldData($val);
                $val['date'] = date('Y-m-d H:i', $val['createtime']);
                $coach = Db::name('user')->where('id','=',$val['pid'])->fieldRaw('nickname,avatar,mobile,id,createtime,set_id,wechat_number')->find();
                if($coach){
                    $coach['set_name'] = Db::name('set')->where('id', '=', $coach['set_id'])->value('name');
                }
                $val['coach'] = $coach;
              
            }
        return $this->success('ok', $list);
    }


    /**
     * 获取辅导员邀请店铺列表
     *
     * @param integer $page 1
     * @param integer $limit 10
     * @param string $search 搜索
     * @return void
     * @Action
     */
    public function get_coach_store_list(?int $page = 1, ?int  $limit = 10, ?string $search = null)
    {
        $page = $page ?: 1;
        $limit = $limit ?: 10;

        if ($search) {
            $data['name'] = ['like', "%" . $search . "%"];
        }
        $data['pid'] = $this->auth->user()->id;

        $list = Db::name('store')->whereEx($data)->page($page, $limit)->orderRaw('id desc')->select()->getArray();

        if ($list)
            foreach ($list as $key => &$val) {
                // $val['mobile'] = $this->HideMobile($val['mobile']);
                // $this->ChangeFieldData($val);
                $val['date'] = date('Y-m-d H:i', $val['createtime']);
                $coach = Db::name('user')->where('id','=',$val['pid'])->fieldRaw('nickname,avatar,mobile,id,createtime,set_id,wechat_number')->find();
                if($coach){
                    $coach['set_name'] = Db::name('set')->where('id', '=', $coach['set_id'])->value('name');
                }
                $val['coach'] = $coach;
            }
        return $this->success('ok', $list);
    }
}
